
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class QuizController
{

	public QuizController(JFrame frame, Quiz quiz)
	{
		itsFrame = frame;
		itsQuiz = quiz;
		userAnswers =  new String[itsQuiz.size()];
		for(int i = 0; i < itsQuiz.size(); ++i)
		{
			userAnswers[i] = new String("");
		}
	}
	
	public void go()
	{
		StartView view = new StartView(itsQuiz.getQuizname(), this);
		view.display(itsFrame);
	}
	
	public void done()
	{
		System.exit(0);
	}
	
	public void start()
	{
		currentQuestion = 0;
		ask();
	}
	
	private void ask()
	{
		Question q = itsQuiz.getQuestion(currentQuestion);
		if(q != null)
		{
			IView questionView = QuestionViewFactory.createQuestionView(q, this);
			questionView.display(itsFrame);
		}
	}
	
	public void prev()
	{
		currentQuestion--;
		ask();
	}
	
	public void next()
	{
		currentQuestion++;
		if(currentQuestion < itsQuiz.size())
		{
			ask();
		}
		else
		{
			showResults();
		}
	}
	
	public void showResults()
	{
		boolean results[] = new boolean[itsQuiz.size()];
		for(int i = 0; i < itsQuiz.size(); ++i)
		{
			results[i] = (userAnswers[i].equals(itsQuiz.getQuestion(i).getAnswer()));
		}
		ResultsModel model = new ResultsModel(results);
		ResultsSummaryView view = new ResultsSummaryView(this, model);
		view.display(itsFrame);
	}
	
	public void showAnsweredQuestion(int index, Window parent)
	{
		IView view = ResultViewFactory.createResultView(itsQuiz.getQuestion(index), userAnswers[index]);
		view.display(parent);
	}
	
	public void setUserAnswer(String userAnswer)
	{
		userAnswers[currentQuestion] = userAnswer;
	}
	
	public String getCurrentResult()
	{
		return userAnswers[currentQuestion];
	}
	
	public void setCurrentResult(String result)
	{
		userAnswers[currentQuestion] = result;
	}
	
	public int getCurrentQuestion()
	{
		return currentQuestion;
	}
	
	private int currentQuestion = 0;
	private Quiz itsQuiz;
	private JFrame itsFrame;
	private String[] userAnswers;
}
